package com.bw.controller.pay;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.orders.PiOrder;
import com.bw.entity.orders.PiOrderLog;
import com.bw.entity.pay.PiPayLog;
import com.bw.req.OrderPay;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.orders.IPiOrderLogService;
import com.bw.service.orders.IPiOrderService;
import com.bw.service.pay.IPiPayLogService;
import com.bw.service.user.ITbUserService;
import com.bw.utils.aliPay.AlipayConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-19
 */
@RestController
@RequestMapping("payLog")
public class PiPayLogController {

    @Autowired
    private IPiPayLogService piPayLogService;
    @Autowired
    private IPiOrderService orderService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private IPiOrderLogService orderLogService;

    @Autowired
    private IPiCustomerService piCustomerService;

    private final Logger logger= LoggerFactory.getLogger(PiPayLogController.class);


    /**
     * @Description:支付日志
     * @Author: 周明丽
     * @Date: 2020/6/21 10:51
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("list/{id}")
    public ResponseResult list(@PathVariable("id") Long id) {
        logger.info("查询支付记录开始");
        ResponseResult result = ResponseResult.SUCCESS();

        try {

            //根据id查询客户姓名

            //根据客户id去查找到所有支付日志

            //查询订单的code;
            PiOrder piOrder = orderService.getById(id);
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("out_trade_no",piOrder.getCode());
            List<PiPayLog> piInvoiceLog = piPayLogService.list(queryWrapper);
            for(PiPayLog piPayLogs:piInvoiceLog){
                piPayLogs.setUserId(piOrder.getCustomerName());
            }
            result.setResult(piInvoiceLog);

        }catch (Exception e){
            logger.error("查询支付记录失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("查询支付记录失败:" + e.toString());
        }

        return result;
    }




    /**
     * @Description:跳到付款页面
     * @Author: 周明丽
     * @Date: 2020/6/29 22:01
     * @param piOrder:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("payMoney")
    public ResponseResult saveOrder(@RequestBody OrderPay piOrder){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            logger.info("付款页面开始");

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ piOrder.getCode() +"\","
                    + "\"total_amount\":\""+ piOrder.getPriceIt() +"\","
                    + "\"subject\":\""+ piOrder.getRemarks() +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //支付日志
            PiPayLog piPayLog = new PiPayLog();
            //piPayLog.setTradeNo();//流水号
            piPayLog.setOutTradeNo(piOrder.getCode());//订单编号
            piPayLog.setTotalAmount(piOrder.getPriceIt());//支付金额
            piPayLog.setCreateTime(new Date());//创建时间
            piPayLog.setUserId(piOrder.getCustomerName());//操作人
            piPayLog.setTradeState("支付中");
            piPayLogService.save(piPayLog);
            PiOrder order=orderService.getById(piOrder.getId());
            order.setState(4);//转合同
            order.setUpdateDate(new Date());
            order.setUpdateUser(piOrder.getUpdateUser());
            System.out.println(order);
            orderService.saveOrUpdate(order);
            logger.info("修改成功");
            //订单日志
            PiOrderLog piOrderLog = new PiOrderLog();
            piOrderLog.setTbId(order.getTbId());
            piOrderLog.setUserName(userService.getById(order.getTbId()).getUserName());
            piOrderLog.setOrderId(order.getId());
            piOrderLog.setRemarks("转合同订单记录");
            orderLogService.save(piOrderLog);
            result.setMessage("修改成功");

            result.setResult(alipayClient.pageExecute(alipayRequest).getBody());

        } catch (Exception e) {
            logger.error("支付失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("支付失败" + e.toString());
        }
        logger.info("付款页面结束");
        return result;
    }

    /**
     * @Description:支付宝同步通知
     * @Author: 周明丽
     * @Date: 2020/6/29 18:54
     * @param request:
     * @return: com.bw.resp.ResponseResult
     **/
    @RequestMapping("checkSign")
    public ResponseResult checkSign(HttpServletRequest request){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            logger.info("验证签名开始");

            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名


            if(!signVerified){




                //验证签名成功
                result.setMessage("支付成功");
                //修改订单的状态为已支付
                //记录日志
                String orderCode=request.getParameter("out_trade_no");
                QueryWrapper wrapper=new QueryWrapper();
                wrapper.eq("code",orderCode);
                PiOrder order=orderService.getOne(wrapper);
                String totalMoney = request.getParameter("total_amount");
                String productCode = request.getParameter("product_code");
                String tradeno = request.getParameter("trade_no");
                PiPayLog piPayLog = new PiPayLog();
                piPayLog.setCreateTime(new Date());
                piPayLog.setOutTradeNo(orderCode);
                piPayLog.setTotalAmount(order.getPriceIt());
                piPayLog.setPayType("0");
                piPayLog.setTradeState("支付完成");
                piPayLog.setUserId(order.getCustomerName());
                //转成bigDecimal类型
                BigDecimal bigDecimal=new BigDecimal(totalMoney);
                piPayLog.setTotalAmount(bigDecimal);
                piPayLog.setTradeNo(productCode);
                piPayLog.setTradeNo(tradeno);
                piPayLogService.save(piPayLog);
                //userId,支付类型，支付状态
              } else{
                String orderCode=request.getParameter("out_trade_no");
                QueryWrapper wrapper=new QueryWrapper();
                wrapper.eq("code",orderCode);
                PiOrder order=orderService.getOne(wrapper);
                PiPayLog piPayLog = new PiPayLog();
                piPayLog.setCreateTime(new Date());
                piPayLog.setOutTradeNo(orderCode);
                piPayLog.setTotalAmount(order.getPriceIt());
                piPayLog.setPayType("0");
                piPayLog.setTradeState("支付失败");
                piPayLog.setUserId(order.getCustomerName());
                piPayLogService.save(piPayLog);
                logger.error("支付失败");
                result.setSuccess(false);
                result.setMessage("支付失败" );
            }

        } catch (Exception e) {
            logger.error("验证签名失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("验证签名失败" + e.toString());
        }
        logger.info("验证签名结束");
        return result;
    }


    /**
     * @Description:支付宝异步通知
     * @Author: 周明丽
     * @Date: 2020/6/29 18:54
     * @param request:
     * @return: com.bw.resp.ResponseResult
     **/
    @RequestMapping("checkNotify")
    public String checkNotify(HttpServletRequest request){
        String result = "success";
        try {
            logger.error("验证签名开始");

            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //验证码签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            if(!signVerified){
                //验证签名成功
                //修改订单的状态为已支付
                String orderCode=request.getParameter("out_trade_no");
                QueryWrapper wrapper=new QueryWrapper();
                wrapper.eq("code",orderCode);
                PiOrder order=orderService.getOne(wrapper);
                String totalMoney = request.getParameter("total_amount");
                String productCode = request.getParameter("product_code");
                String tradeno = request.getParameter("trade_no");
                PiPayLog piPayLog = new PiPayLog();
                piPayLog.setCreateTime(new Date());
                piPayLog.setOutTradeNo(orderCode);
                piPayLog.setPayType("0");
                piPayLog.setTradeState("支付完成");
                piPayLog.setUserId(order.getCustomerName());
                //转成bigDecimal类型
                BigDecimal bigDecimal=new BigDecimal(totalMoney);
                piPayLog.setTotalAmount(bigDecimal);
                piPayLog.setTradeNo(productCode);
                piPayLog.setTradeNo(tradeno);
                piPayLogService.save(piPayLog);

                //记录日志
            }else{
                String orderCode=request.getParameter("out_trade_no");
                QueryWrapper wrapper=new QueryWrapper();
                wrapper.eq("code",orderCode);
                PiOrder order=orderService.getOne(wrapper);
                PiPayLog piPayLog = new PiPayLog();
                piPayLog.setCreateTime(new Date());
                piPayLog.setOutTradeNo(orderCode);
                piPayLog.setPayType("0");
                piPayLog.setTradeState("支付失败");
                piPayLog.setUserId(order.getCustomerName());
                piPayLogService.save(piPayLog);
                logger.error("支付失败");
                result="false";
                result="支付失败" ;
                logger.error("支付失败");
                result="异常error";
            }

        } catch (Exception e) {
            logger.error("验证签名失败"+e.toString());
            result="异常error";
        }
        logger.error("验证签名结束");
        return result;
    }



}
